
--------------BIBLIOTECAS-----------------------
physics = require( "physics" );
lime = require("lime.lime");
------------------ CONFIGURA A FÍSICA-------------------------------
physics.start();
physics.setGravity(0,0);
physics.setScale(100);
physics.setPositionIterations(24)
physics.setVelocityIterations( 8 )
physics.setTimeStep(0);



----------CARREGA MAPA----------------
Map = require("Map");
map = Map:MapInstance();
local physical = lime.buildPhysical(map);

-----------CARREGA O PLAYER-----------
local Player = require("Player");
local player = Player:PlayerInstance()

---------------------- CONFIGURA O SISTEMA------------------------------------------
display.setStatusBar(display.HiddenStatusBar);

-------------------------CENTRO DA TELA, SE NECESSÁRIO PARA REFERÊNCIA FUTURA------------------------------------
local centerX = display.contentCenterX;
local centerY = display.contentCenterY;

---------------------------ESTADOS DO PLAYER, DEFINIRÁ SE O PLAYER DEVE SE MOVER OU NÃO-----------------------------------------------
local stateIdle = "Idle"
local stateMoving = "Moving"

-----------------------------VALORES DE DIREÇÃO--------------------------------------------------------
local directionRight = -1
local directionLeft  = 1
local directionUp = -1
local directionDown = 1
local directionStandard = 0

-----------------------------BOOLEANAS DE DIREÇÃO----------------------------------------------------------------
local _isUp = false
local _isRight = false
local _isLeft = false
local _isDown = false


local Arrow = require("Arrows");
local arrows = Arrow:ArrowsInstance();



-------------------------------------- FUNÇÃO QUE CARREGA TEXTURAS, DESENHA O MAPA E POSICIONA OBJETOS
local function Draw()

	-----------------------------CRIA O PLAYER E O POSICIONA------------------------------------------
	player:Position()
	player:SetPhysics()
	----------------------------CRIA AS SETAS DO CONTROLADOR E AS POSICIONA----------------------------------------------
	arrows.Position();
	
	
end --- local function Draw()
	

local function _onTouchMove(event)
		---------------------------------------  MOVIMENTAÇÃO PELAS SETAS  --------------------------------------------------------------
		-------------------------------QUANDO O A SETA É TOCADA, O EVENTO É CHAMADO--------------------------------------------
		if(event.phase == "began") then
			if (event.x < arrows.up.x + arrows.up.width/2) and (event.x > arrows.up.x - arrows.up.width/2 )
			and event.y < arrows.up.y + arrows.up.height/2  
			and  event.y > arrows.up.y - arrows.up.height/2 then
					------------------------------------------ DIREÇÃO E ESTADO DE MOVIMENTO----------------------------------------------
					player.direction = directionUp
					player.state = stateMoving
					-----------------------------------DEFINE A DIREÇÃO ATUAL COMO VERDADEIRA E TODAS AS OUTRAS COMO FALSAS------------------------------------------
					-----------------------------------PARA POSTERIOR VERIFICAÇÃO----------------------------------------------------------------
					_isUp = true
					_isRight = false
					_isDown = false
					_isLeft = false
			end --- if event.x < up.x + up.width/2 and event.x > up.x - up.width/2 
			if (event.x < arrows.left.x+arrows.left.width/2) and  (event.x > arrows.left.x-arrows.left.width/2 )
			
				and event.y < arrows.left.y+arrows.left.height/2 
				and event.y > arrows.left.y-arrows.left.height/2 then
					player.direction = directionLeft
					player.state = stateMoving
					_isUp = false
					_isRight = false
					_isDown = false
					_isLeft = true
			end --if event.x < left.x+left.width/2 and event.x > left.x-left.width/2 
			
			if event.x < arrows.right.x+arrows.right.width/2 and event.x > arrows.right.x-arrows.right.width/2 
				and arrows.right.y < arrows.right.y+arrows.right.height/2 
				and event.y > arrows.right.y-arrows.right.height/2 then
					player.direction = directionRight
					player.state = stateMoving
					_isUp = false
					_isRight = true
					_isDown = false
					_isLeft = false
			end ---- if event.x < right.x+right.width/2 and event.x > right.x-right.width/2 
			if event.x < arrows.down.x+arrows.down.width/2 and event.x > arrows.down.x-arrows.down.width/2 
				and event.y < arrows.down.y+arrows.down.height/2 
				and event.y > arrows.down.y-arrows.down.height/2 then
					player.direction = directionDown
					player.state = stateMoving
					_isUp = false
					_isRight = false
					_isDown = true
					_isLeft = false				
			end --- if event.x < down.x+down.width/2 and event.x > down.x-down.width/2 
		----------------------------QUANDO A SETA É SOLTA, O EVENTO É CHAMADO---------------------------------
		elseif(event.phase == "ended" or event.phase == "cancelled") then
				-----------------------PLAYER ENTRA NO ESTADO  OCIOSO, AGUARDA ENTRAR EM MOVIMENTO NOVAMENTE------------------------------------
					player.direction = directionStandard
					player.state = stateIdle
					_isUp = false
					_isRight = false
					_isDown = false
					_isLeft = false
			
		end --------------elseif(event.phase == "ended" or event.phase == "cancelled") then
		
end ---------local function _onTouchMove(event)

-----------------------CALCULA A NOVA POSIÇÃO DO PLAYER DEPENDENDO DO SEU ESTADO------------------------------------------------------
local function _onUpdate(event)
--------------------------APLICA-SE A FORÇA PARA MOVIMENTAR O PLAYER DEPENDENDO DA SUA DIREÇÃO---------------------------------------------------------------
	if(_isUp and player.state == stateMoving) then
		 player:applyForce(0, player.direction * 0.7, player.x, player.y)
	elseif(_isRight and player.state == stateMoving) then
		 player:applyForce(player.direction * 0.7,0 , player.x, player.y)
	elseif(_isLeft and player.state == stateMoving) then
		 player:applyForce(player.direction * 0.7,0 , player.x, player.y)
	elseif(_isDown and player.state == stateMoving) then
		 player:applyForce(0, player.direction * 0.7, player.x, player.y)
	
	-----------------------QUANDO ENTRA NO ESTADO OCIOSO, O PLAYER INICIA MOVIMENTO INERCIAL ATÉ PARAR COMPLETAMENTE------------------------------------------------
	elseif(player.state == stateIdle) then
		local velx, vely = player:getLinearVelocity()
        if velx ~= 0 then
		--------------PARA OCORRER INÉRCIA, MULTIPLICA-SE A COORDENADA POR VALOR DECIMAL, ATÉ QUE ATINJA VELOCIDADE 0----------------------------------------------------
            player:setLinearVelocity(velx * 0.8, vely)
		elseif vely ~= 0 then 
			player:setLinearVelocity(velx , vely * 0.8)
		end ---elseif(player.state == stateIdle) then
	end -- (player.state == stateIdle) then
end -----------local function _onUpdate(event)

-----------SE O PLAYER ENCOSTAR EM ALGUMA CAIXA, DEVE PARAR(INÉRCIA É ANULADA)----------------------------------------------------------
local function _onCollision(self, event)
	if(event.phase == "began") then
		player:setLinearVelocity(0, 0)
	end ------------if(event.phase == "began") then
end -------------  local function _onCollision(self, event)




----------------CHAMA A FUNÇÃO DRAW---------------------------------------------------------
Draw();

------------------EVENTOS E SUAS FUNÇÕES---------------------------------------------------------
Runtime:addEventListener("touch", _onTouchMove)
Runtime:addEventListener("enterFrame", _onUpdate)


player.collision = _onCollision
player:addEventListener("collision", player) 

